<template>
  <div class="tinymce-editor">
    <editor
      v-if="!reloading"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick">
    </editor>
  </div>
</template>

<script>
  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/themes/mobile/theme'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/plugins/code'
  import 'tinymce/icons/default'
  import '../../../public/tinymce/plugins/axupimgs/plugin'// 多图批量上传
  import { postAction, uploadAction, getFileAccessHttpUrl } from '@/api/manage'
  import { getVmParentByName } from '@/utils/util'
  //import axios from 'axios'
  export default {
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        required:false
      },
      triggerChange:{
        type: Boolean,
        default: false,
        required:false
      },
      disabled: {
        type: Boolean,
        default: false
      },
      plugins: {
        type: [String, Array],
        //default: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help paste emoticons autosave'
        default: 'code lists image axupimgs link media table textcolor wordcount contextmenu fullscreen'
      },
      toolbar: {
        type: [String, Array],
        //default: 'code codesample undo redo restoredraft | cut copy paste pastetext | forecolor backcolor searchreplace bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | bullist numlist | formatselect fontselect fontsizeselect | blockquote subscript superscript removeformat | table image media charmap emoticons hr pagebreak insertdatetime print preview'
        default: 'undo redo code |  fontsizeselect | fontselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link unlink image axupimgs media table | removeformat | fullscreen',
        branding:false
      },
      action:{
        type: String,
        required:false
      },
      data:{
        type: Object,
        required:false
      }
    },
    data() {
      return {
        //初始化配置
        init: {
          language_url: '/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          skin_url: '/tinymce/skins/lightgray',
          height: 300,
          plugins: this.plugins,
          toolbar: this.toolbar,
          font_formats: "飞科默认=BlinkMacSystemFont,Helvetica Neue,Helvetica,Segoe UI,Arial,Roboto,PingFang SC,miui,Hiragino Sans GB,Microsoft Yahei,sans-serif;",
          fontsize_formats: "6pt 8pt 9pt 10pt 11pt 12pt 13pt 14pt 15pt 16pt 18pt 24pt 36pt",
          branding: false,
          menubar: false,
          force_p_newlines: false,//换行时去除<p>
          forced_root_block:'',//去除以<p>开头与结尾
          image_dimensions:false,//图片尺寸
          toolbar_drawer: false,
          images_upload_handler: (blobInfo, success, failure) => {
            /*const img = 'data:image/jpeg;base64,' + blobInfo.base64()
            success(img)*/
            let formData = new FormData()
            //console.log(blobInfo.filename())
            if(null !== this.data){
              formData.append('dir',this.data.dir)
            }else{
              formData.append('dir','cms')
            }
            formData.append('file',blobInfo.blob())
            uploadAction('/sys/common/ossUpload',formData).then(response =>{
              if(response.success){
                console.log(response.message)
                success(response.message)
              }else{
                failure('上传失败，请稍后重试！')
              }
            }).catch(b=>{
              failure('上传超时，可能是网速太慢！')
            });
          }
        },
        myValue: this.value,
        reloading: false,
      }
    },
    mounted() {
      //tinymce.init({})
      this.initATabsChangeAutoReload()
    },
    methods: {
      reload() {
        this.reloading = true
        this.$nextTick(() => this.reloading = false)
      },
      onClick(e) {
        console.log("onClick");
        this.$emit('onClick', e, tinymce)
      },
      //可以添加一些自己的自定义事件，如清空内容
      clear() {
        console.log("clear");
        this.myValue = ''
      },

      /**
       * 自动判断父级是否是 <a-tabs/> 组件，然后添加事件监听，自动触发reload()
       *
       * 由于 tabs 组件切换会导致 tinymce 无法输入，
       * 只有重新加载才能使用（无论是vue版的还是jQuery版tinymce都有这个通病）
       */
      initATabsChangeAutoReload() {
        // 获取父级
        let tabs = getVmParentByName(this, 'ATabs')
        let tabPane = getVmParentByName(this, 'ATabPane')
        if (tabs && tabPane) {
          // 用户自定义的 key
          let currentKey = tabPane.$vnode.key
          // 添加事件监听
          tabs.$on('change', (key) => {
            // 切换到自己时执行reload
            if (currentKey === key) {
              this.reload()
            }
          })
          //update--begin--autor:liusq-----date:20210316------for：富文本编辑器tab父组件可能导致的赋值问题------
          this.reload()
          //update--end--autor:liusq-----date:20210316------for：富文本编辑器tab父组件可能导致的赋值问题------
        }else{
          //update--begin--autor:wangshuai-----date:20200724------for：富文本编辑器切换tab无法修改------
          let tabLayout = getVmParentByName(this, 'TabLayout')
          //update--begin--autor:liusq-----date:20210713------for：处理特殊情况excuteCallback不能使用------
          try {
            tabLayout.excuteCallback(() => {
              this.reload()
            })
          } catch (error) {
            if (tabLayout) {
              this.reload()
            }
          }
          //update--end--autor:liusq-----date:20210713------for：处理特殊情况excuteCallback不能使用------
          //update--begin--autor:wangshuai-----date:20200724------for：文本编辑器切换tab无法修改------
        }
      },
    },
    watch: {
      value(newValue) {
        //console.log("value");
        this.myValue = (newValue == null ? '' : newValue)
      },
      myValue(newValue) {
        //console.log("myValue");
        if(this.triggerChange){
          this.$emit('change', newValue)
        }else{
          this.$emit('input', newValue)
        }
      }
    }
  }

</script>
<style scoped>
</style>